const { getUserInfo } = require('../service/user.service')
const { userFormateError, userAlreadyExited, userLoginError, dataNotExist, systemError, paramError } = require('../constant/status.type')
const bcrypt = require('bcryptjs')

const userValidator = async (ctx, next) => {
  try {
    const { user_name, password } = ctx.request.body
    // 合法性
    if (!user_name || !password) {
      console.error('用户名或密码为空', ctx.request.body)
      ctx.app.emit('error', userFormateError, ctx)
      return
    }
    await next()
  } catch (error) {
    console.error(error);
    ctx.app.emit('error', userFormateError, ctx)
  }
}

//合理性
const verifyUser = async (ctx, next) => {
  const { user_name } = ctx.request.body
  try {
    const is_user_name = await getUserInfo({ user_name })
    if (is_user_name) {
      console.error('用户名已存在', { user_name });
      ctx.app.emit('error', userAlreadyExited, ctx)
      return
    }
    await next()
  } catch (err) {
    console.error('验证用户名合理性失败', err);
    ctx.app.emit('error', userAlreadyExited, ctx)
    return
  }
}

//加密
const crpytPassword = async (ctx, next) => {
  try {
    const { password } = ctx.request.body
    const salt = bcrypt.genSaltSync(10)
    // hash保存的是 密文
    const hash = bcrypt.hashSync(password, salt)
    ctx.request.body.password = hash

    await next()
  } catch (error) {
    if (!ctx.request.body || !ctx.request.body.password) {
      console.error('密码为空');
      ctx.app.emit('error', paramError, ctx)
    }
    console.error('验证用户名合理性失败', error);
  }
}

//校验密码
const comparePassword = async (ctx, next) => {
  try {
    const { user_name, password } = ctx.request.body
    const sqlRes = await getUserInfo({ user_name })
    if (sqlRes) {
      // hash保存的是 密文
      const isMatch = bcrypt.compareSync(password, sqlRes.password);
      if (!isMatch) {
        console.error('账号或密码错误');
        ctx.app.emit('error', userLoginError, ctx)
        return
      }
    } else {
      ctx.app.emit('error', dataNotExist, ctx)
      return
    }
  } catch (err) {
    console.error('登录验证失败', err);
    ctx.app.emit('error', systemError, ctx)
    return
  }
  await next()
}


module.exports = {
  userValidator,
  verifyUser,
  crpytPassword,
  comparePassword
}